﻿using AiMoWindows.Compiler;
using AiMoWindows.Server;
using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
using System.Diagnostics;

namespace AiMoWindows.MainActions
{
    static class ActionsUtils
    {
        public static string FormatException(this Exception ex)
        {
            return CSharpObjectFormatter.Instance.FormatException(ex);
        }
        public static async Task OpenPath(string path)
        {
            if (System.IO.Directory.Exists(path) || System.IO.File.Exists(path))
            {
                await Task.Run(() =>
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = path,
                        UseShellExecute = true,
                    };
                    Process.Start(startInfo);
                });
            }
        }
        public static async void SelectFileInWindows(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                await Task.Run(() =>
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = "explorer.exe",
                        Arguments = "/select, " + filePath,
                        UseShellExecute = true,
                    };
                    Process.Start(startInfo);
                });
            }
        }
        public static async void OpenWebsite(string url)
        {
            await Task.Run(() =>
            {
                try
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = url, // 确保网址以http或https开头
                        UseShellExecute = true // 在.NET Core或.NET 5及以上版本中需要设置
                    };
                    Process.Start(startInfo);
                }
                catch (Exception ex)
                {
                    string error = $"Cannot open website {url}\r\n" + ex.Message;
                    System.Windows.MessageBox.Show(error);
                }
            });
        }
        public static void OpenTutorialWeb()
        {
            OpenWebsite(ServerHelper.CommunityAddress);
        }
        internal static readonly string shareSpliter = "[52570552A939]";
        internal static readonly string descriptionNewLine = "%0A%20%20%20%20%20%20%20%20";
        internal static readonly string[] separator = new string[] { "\r\n", "\n" };
        public static void OpenWebWithShareKey(string shareKey, string name, string description)
        {
            if (ServerHelper.LogInAsCommunityUser)
            {
                string[] lines = description.Split(separator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
                string newLines = string.Join(descriptionNewLine, lines.Where(x => !string.IsNullOrWhiteSpace(x)));
                if (newLines.Length > 200) newLines = newLines[..200];
                string web = ServerHelper.CommunityShareAddress +
                $"{shareSpliter}#新发现{shareSpliter}" +
                $"{name}{shareSpliter}{newLines.Replace("//", "")}{shareSpliter}{shareKey}{shareSpliter}" +
                $"{ServerHelper.UserName}{shareSpliter}{ServerHelper.EncodedPassword}{shareSpliter}";
                OpenWebsite(web);
            }
        }
        public static string CreateShareKey(string userName)
        {
            return userName + "-" + Guid.NewGuid().ToString()[24..].ToUpper();
        }
        public static void SetTextToClipboard(string text)
        {
            //System.Threading.ThreadStateException:
            //“在可以调用 OLE 之前，必须将当前线程设置为单线程单元(STA)模式。
            //请确保您的 Main 函数带有 STAThreadAttribute 标记。”
            Thread t = new Thread(() => { System.Windows.Forms.Clipboard.SetText(text); });
            t.TrySetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
        public static string ReplaceCode(string code)
        {
            code = code.Replace("Console.WriteLine(", "Print(").Replace("Console.Write(", "Print(");
            return code;
        }
        public static string[] ConvertToLines(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return Array.Empty<string>();
            return Utils.FixNewlines(text).Split(separator, StringSplitOptions.None);
        }

        public static int GetFirstNonWhitespacePosition(this Microsoft.CodeAnalysis.Text.TextLine textLine)
        {
            // 获取文本内容
            string text = textLine.Text?.ToString(textLine.Span) ?? "";
            // 遍历文本内容，找到第一个非空格字符
            for (int i = 0; i < text.Length; i++)
            {
                if (!char.IsWhiteSpace(text[i]))
                {
                    // 返回该字符在行中的位置
                    return i;
                }
            }
            // 如果没有找到非空格字符，返回 -1
            return -1;
        }
    }
}
